package com.yao.service.Impl;

import com.yao.context.BaseContext;
import com.yao.mapper.ArticleMapper;
import com.yao.mapper.CategoryMapper;
import com.yao.pojo.Article;
import com.yao.pojo.ArticleQuery;
import com.yao.pojo.Category;
import com.yao.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class CategoryServiceImpl implements CategoryService {

    private CategoryMapper categoryMapper;
    private ArticleMapper articleMapper;

    @Autowired
    public void CategoryService(CategoryMapper categoryMapper,ArticleMapper articleMapper){
        this.categoryMapper = categoryMapper;
        this.articleMapper = articleMapper;
    }

    /**
     * 查找所有分类
     * @return
     */
    @Override
    public List<Category> getCategoryList() {
        List<Category> categoryList = categoryMapper.getAllCategory();
        return categoryList;
    }

    /**
     * 新增文文章分类
     * @param category
     */
    @Override
    public void addCategory(Category category) {
        category.setCreateUser(BaseContext.getCurrentId());
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.insertCategory(category);
    }

    /**
     * 修改文章分信息
     * @param categoryParam
     */
    @Override
    public Boolean changeCategory(Category categoryParam) {
        Category category = categoryMapper.selectCategoryById(categoryParam.getId());

        if (category.getCreateUser() != BaseContext.getCurrentId()) return false;
        categoryParam.setUpdateTime(LocalDateTime.now());

        categoryMapper.changeCategory(categoryParam);
        return true;
    }

    /**
     * 根据ID获取文章分类信息
     * @param id
     * @return
     */
    @Override
    public Category getCategory(Integer id) {
        Category category = categoryMapper.selectCategoryById(id);
        return category;
    }

    /**
     * 根据ID删除文章分类
     * @param id
     * @return
     */
    @Override
    public int deleteCategory(Integer id) {
        // 查找该分类是否还有文章
        ArticleQuery articleQuery = ArticleQuery.builder()
                .categoryId(id)
                .build();
        List<Article> articleList = articleMapper.selectArticle(articleQuery);
        if (articleList != null && articleList.size() > 0) return 1;

        //查找修改者是否是创建者
        Category categoryParam = Category.builder()
                .id(id)
                .build();
        Category category = categoryMapper.selectCategoryById(categoryParam.getId());
        if (category.getCreateUser() != BaseContext.getCurrentId()) return 2;

        //修改
        categoryMapper.deleteCategoryById(id);
        return 0;
    }


}
